<template>
  <div class="sysdict-select-wrapper" ref="sysdictRemoteSelectWrapperRef">
    <a-select
      v-bind="$attrs"
      placeholder="请选择"
      allow-search
      show-footer-on-empty
      :trigger-props="{ updateAtScroll: true }"
      :popup-container="mergedPopupContainer"
      @change="changeFn"
    >
      <a-option
        v-show="addable == false ? true : !it.disabled"
        :disabled="disabledList?.includes(it.value)"
        v-for="it in options"
        :key="it.value"
        :value="it.value"
      >
        {{ it.label }}
      </a-option>
      <template #footer v-if="addable">
        <a-button type="text" @click="editSysDict" long>新增+</a-button>
      </template>
    </a-select>

    <SysdictModal ref="sysdictModal" :maxLength="maxLength" @save="saveOk" />
  </div>
</template>

<script setup lang="ts" name="SysdictSelect">
  import SysdictModal from './sysdict-modal.vue'
  import { computed, ref, onMounted } from 'vue'
  import { useSysDict, sysDictOrigin, dispacthSysDict } from '@/hooks/useDict'
  import { systemCodeDetail } from '@/api/system/system'

  const props = defineProps({
    code: String,
    popupContainer: [String, Object],
    disabledList: Array<number>,
    // 给筛选框用的
    addable: {
      type: Boolean,
      default: true,
    },
    maxLength: {
      type: Number,
      default: 9999,
    },
  })
  const emit = defineEmits(['change', 'mustGet', 'loadData'])

  const mergedPopupContainer = ref(props.popupContainer)
  const sysdictRemoteSelectWrapperRef = ref()
  if (!props.popupContainer) {
    onMounted(() => {
      mergedPopupContainer.value = sysdictRemoteSelectWrapperRef.value
      msgGet()
    })
  }

  const code = props.code + ''
  useSysDict([code])
  const options = computed(() => {
    let res = sysDictOrigin[code]
    if (res && res.length > 0) {
      emit('loadData', res)
    }

    return res
  })

  const sysdictModal = ref()

  const changeFn = (val: string) => {
    if (val) {
      const option = options.value.find((it: any) => it.value == val)
      emit('change', val, option?.label)
    } else {
      emit('change', val)
    }
  }

  // 修改系统参数dict
  const editSysDict = () => {
    sysdictModal.value.show(null, code)
  }
  // 系统参数修改
  const saveOk = () => {
    // 更新dict
    dispacthSysDict(code)
    // 通知必填非必填
    msgGet()
  }
  const isControlMust = ref(0)
  // 获取必填或非必填，并通知页面
  const msgGet = () => {
    systemCodeDetail({ dictCode: code }).then((res: { result: { isControlMust: number } }) => {
      isControlMust.value = res.result.isControlMust
      emit('mustGet', code, isControlMust.value)
    })
  }
</script>

<style lang="less" scoped>
  .sysdict-select-wrapper {
    position: relative;
    width: 100%;
  }
</style>
